package com.tensquare.user.service;

import com.tensquare.user.dao.AdminDao;
import com.tensquare.user.pojo.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import util.IdWorker;

import javax.transaction.Transactional;

/**
 * Created by WF on 2020/10/24 9:28
 */
@Service
@Transactional
public class AdminService {
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    //1.添加管理员
    public void add(Admin admin) {
        //1.1)加密密码
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        admin.setId(idWorker.nextId() + "");
        //1.2)添加到数据库中
        adminDao.save(admin);
    }

    //2.管理员登录
    public Admin login(Admin admin) {
        //2.1)根据登录名得到登录用户
        Admin loginAdmin = adminDao.findByLoginname(admin.getLoginname());
        //2.2)比对密码
        if(loginAdmin != null){
            if(passwordEncoder.matches(admin.getPassword(),loginAdmin.getPassword())){
                return loginAdmin;
            }
        }
        return null;
    }

    //3.删除管理员
    public void delete(String adminId) {
        adminDao.deleteById(adminId);
    }
}
